package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.ShortURLService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description:
 */
@Service
@Slf4j
public class ShortURLServiceImpl implements ShortURLService {

    final String SHORT_URL_KEY_NAME = "short::url";
    final String SHORT_ID = "short::id";


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public String transfer(String url) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        long id = generateID();
        log.info("id:{}", id);
        //HSET 
        //在 redis 中保留映射关系
        opsForHash.put(SHORT_URL_KEY_NAME, id + "", url);
        String res = SHORT_HOST + "/" + id;
        log.info("short url:{}", res);
        return res;
    }

    @Override
    public String getRaw(String id) {
        HashOperations<String, Object, Object> opsForHash = stringRedisTemplate.opsForHash();
        Object o = opsForHash.get(SHORT_URL_KEY_NAME, id);
        if (o != null) {
            return o.toString();
        }
        return null;
    }

    /**
     * 生成map 中的 key
     *
     * @return
     */
    private Long generateID() {
        ValueOperations<String, String> valueOperations = stringRedisTemplate.opsForValue();
        Long increment = valueOperations.increment(SHORT_ID);
        return increment;
    }

}
